package cn.net.autocode.platform.entrance;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.config.SpringProfileConfig;
import cn.net.autocode.platform.design.handle.AutoCodeHandle;
import cn.net.autocode.platform.design.webclient.AcWebClient;
import cn.net.autocode.platform.viewEngine.AutoCodeThymeleaf;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("platform/entrance")
public class MenuEntrance {


    private final Dao dao;

    private final SpringProfileConfig profileConfig;

    private final AcWebClient acWebClient;

    private static final List<String> PLATFORM_HTML = new ArrayList<>();

    static{
        PLATFORM_HTML.add("platformDict/index");
        PLATFORM_HTML.add("platformTable/index");
        PLATFORM_HTML.add("platformFunction/index");
        PLATFORM_HTML.add("platformSetting/index");
        PLATFORM_HTML.add("platformSetting/online");
        PLATFORM_HTML.add("platformMenus/index");
        PLATFORM_HTML.add("platformMenus/appIndex");
        PLATFORM_HTML.add("platformMenus/sysOrgan");
        PLATFORM_HTML.add("platformQbe/index");
        PLATFORM_HTML.add("platformWorkflow/index");
        PLATFORM_HTML.add("platformWorkflow/auditType");
        PLATFORM_HTML.add("platformWorkflow/wfField");
        PLATFORM_HTML.add("platformExcel/index");
        PLATFORM_HTML.add("platformRestApi/index");
        PLATFORM_HTML.add("platformAssistant/assistant");
        PLATFORM_HTML.add("platformOrgan/organMenus");
        PLATFORM_HTML.add("platformRole/publicRole");
        PLATFORM_HTML.add("platformRole/index");
        PLATFORM_HTML.add("platformRole/ugroup");
        PLATFORM_HTML.add("platformDingTalk/config");
    }

    private final Dao dictDao;

    public MenuEntrance(Dao dao, SpringProfileConfig profileConfig, AcWebClient acWebClient, @Qualifier("dictDao")Dao dictDao) {
        this.dao = dao;
        this.profileConfig = profileConfig;
        this.acWebClient = acWebClient;
        this.dictDao = dictDao;
    }

    @RequestMapping("{menuId}")
    public ModelAndView view(@PathVariable("menuId") String menuId) throws IOException {
        ModelAndView mav = new ModelAndView();

        JSONObject menu = dao.queryJSON("select * from sys_menus where id=?",menuId);
        if(menu.isEmpty()){
            throw new RuntimeException("菜单信息错误！");
        }else{
            //默认参数设置
            String paramStr = menu.getString("menuParam");
            JSONObject params = new JSONObject();
            if(StrUtil.isNotBlank(paramStr)){
                try {
                    params = JSON.parseObject(paramStr);
                } catch (Exception e) {
                    //
                }
            }

            for (Map.Entry<String, Object> entry : params.entrySet()) {
                mav.addObject(entry.getKey(), entry.getValue());
            }

            //判定菜单url是否存在
            String url = menu.getString("url");
            if (url==null || url.isBlank()){
                throw new RuntimeException("没有维护菜单URL信息！");
            }else{
                //菜单路径处理
                url = url.replace("\\", "/");
                if(url.charAt(0) == '/'){
                    url = url.substring(1);
                }
                if(url.endsWith("/")){
                    url = url.substring(0,url.length()-1);
                }
            }

            //菜单调整处理
            if(PLATFORM_HTML.contains(url)&&!AutoCodeHandle.getAppName().trim().equals("autocode")){
                ClassLoader classLoader = MenuEntrance.class.getClassLoader();
                InputStream inputStream = classLoader.getResourceAsStream("html/"+url+".html");
                byte[] bytes = inputStream.readAllBytes();
                String html = new String(bytes, StandardCharsets.UTF_8);
                View view = new AutoCodeThymeleaf(html);
                mav.setView(view);
            }else{
                //菜单跳转处理
                String internalOrExternal = menu.getString("internalOrExternal");
                if("0".equals(internalOrExternal)){
                    //获取page对应的id
                    String[] paths = url.split("/");
                    String html;
                    if(profileConfig.getProfile().equals("dev")){
                        JSONObject param = new JSONObject();
                        param.put("categoryCode",paths[0]);
                        param.put("code",paths[1]);
                        html = acWebClient.pageView(param);
                    }else{
                        html = dictDao.queryValue("select ac_page_versions.html from ac_page,ac_page_versions where ac_page.id=ac_page_versions.page_id and ac_page.version=ac_page_versions.version and category_code=? and code=?", String.class,paths[0],paths[1]);
                    }
                    View view = new AutoCodeThymeleaf(html);
                    mav.setView(view);
                }else if("2".equals(internalOrExternal)){

                }else{
                    mav.setViewName(url);
                }
            }
        }
        return mav;
    }

}
